package com.bookkeeping.bookkeepingapi.web.api;


import com.alibaba.fastjson.JSON;
import com.bookkeeping.bookkeepingapi.model.BookKeep;
import com.bookkeeping.bookkeepingapi.model.User;
import com.bookkeeping.bookkeepingapi.repository.BookKeepRepository;
import com.bookkeeping.bookkeepingapi.repository.UserRepository;
import com.bookkeeping.bookkeepingapi.service.BookKeepService;
import com.bookkeeping.bookkeepingapi.service.dto.BookKeepDto;
import com.bookkeeping.bookkeepingapi.service.dto.ReturnDto;
import com.bookkeeping.bookkeepingapi.service.util.JwtUtil;
import com.bookkeeping.bookkeepingapi.web.query.BookKeepQuery;
import com.bookkeeping.bookkeepingapi.web.vm.BookKeepVM;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api") //下面所有接口前缀都有api
@AllArgsConstructor
public class BookKeepControler {
    private final BookKeepRepository bookKeepRepository;
    private final BookKeepService bookKeepService;
    private final UserRepository userRepository;

    @GetMapping("book-keep/{id}")
    public String get(@PathVariable Integer id,HttpServletRequest request){
        //获取jwt
        String token = JwtUtil.getJwtFromRequest(request);
        if(StringUtils.isBlank(token)){
            return JSON.toJSONString(new ReturnDto(-1, "非法请求", null));
        }
        String userId;
        try {
            userId = JwtUtil.parseToken(token);
        }catch (Exception e){
            return JSON.toJSONString(new ReturnDto(-9, "token过期", null));
        }
        Optional<User> userOptional = userRepository.findById(Integer.parseInt(userId));
        if(!userOptional.isPresent()){
            return JSON.toJSONString(new ReturnDto(-1, "不存在该用户", null));
        }

        Optional<BookKeep> bookKeep=bookKeepRepository.findById(id);
        if(!bookKeep.isPresent()){
            return JSON.toJSONString(new ReturnDto(-1,"系统中不在该数据",null));
        }
        return JSON.toJSONString((new ReturnDto(1,"查询成功",new BookKeepDto(bookKeep.get()))));
    }

    //获取列表接口
    @GetMapping("/book-keeps")
    public String getList(HttpServletRequest request, BookKeepQuery query) {
        //获取jwt
        String token = JwtUtil.getJwtFromRequest(request);
        if(StringUtils.isBlank(token)){
            return JSON.toJSONString(new ReturnDto(-1, "非法请求", null));
        }
        String userId;
        try {
            userId = JwtUtil.parseToken(token);
        }catch (Exception e){
            return JSON.toJSONString(new ReturnDto(-9, "token过期", null));
        }
        Optional<User> userOptional = userRepository.findById(Integer.parseInt(userId));
        if(!userOptional.isPresent()){
            return JSON.toJSONString(new ReturnDto(-1, "不存在该用户", null));
        }
        //查询列表
        List<BookKeepDto> list=bookKeepRepository.findByYearAndMonthAndUserId(query.getYear(),query.getMonth(),Integer.parseInt(userId)).stream().map(x->new BookKeepDto(x)).collect(Collectors.toList());
        return JSON.toJSONString(new ReturnDto(1,"查询成功",list));
    }
    //获取最近三天的记账记录接口
    @GetMapping("/book-keeps/recent-3-days")
    public String getRecentThreeDays(HttpServletRequest request) {
        // 获取jwt
        String token = JwtUtil.getJwtFromRequest(request);
        if (StringUtils.isBlank(token)) {
            return JSON.toJSONString(new ReturnDto(-1, "非法请求", null));
        }
        String userId;
        try {
            userId = JwtUtil.parseToken(token);
        } catch (Exception e) {
            return JSON.toJSONString(new ReturnDto(-9, "token过期", null));
        }
        Optional<User> userOptional = userRepository.findById(Integer.parseInt(userId));
        if (!userOptional.isPresent()) {
            return JSON.toJSONString(new ReturnDto(-1, "不存在该用户", null));
        }
        LocalDate today = java.time.LocalDate.now();
        LocalDate threeDaysAgo = today.minusDays(2); // 包含今天共3天
        List<BookKeepDto> list = bookKeepRepository
                .findByUserIdAndBookKeepDateBetween(Integer.parseInt(userId), threeDaysAgo, today)
                .stream().map(BookKeepDto::new).collect(Collectors.toList());
        return JSON.toJSONString(new ReturnDto(1, "查询成功", list));
    }
    //创建记账数据接口
    @PostMapping("/book-keep")
    public String create(@RequestBody BookKeepVM bookKeepVM, HttpServletRequest request) {
        //获取jwt
        String token = JwtUtil.getJwtFromRequest(request);
        if(StringUtils.isBlank(token)){
            return JSON.toJSONString(new ReturnDto(-1, "非法请求", null));
        }
        String userId;
        try {
            userId = JwtUtil.parseToken(token);
        }catch (Exception e){
            return JSON.toJSONString(new ReturnDto(-9, "token过期", null));
        }
        Optional<User> userOptional = userRepository.findById(Integer.parseInt(userId));
        if(!userOptional.isPresent()){
            return JSON.toJSONString(new ReturnDto(-1, "不存在该用户", null));
        }
        //检验必填字段
        if (StringUtils.isBlank(bookKeepVM.getCagegory())) {
            return JSON.toJSONString(new ReturnDto(-1, "分类必填", null));
        }
        if (bookKeepVM.getBookKeepDate() == null) {
            return JSON.toJSONString(new ReturnDto(-1, "记账时间必填", null));
        }
        if (bookKeepVM.getType() == null) {
            return JSON.toJSONString(new ReturnDto(-1, "记账类型必填", null));
        }
        //这里大家可以多加一些判断，比如，金额传0报错，
        if (bookKeepVM.getPrice() == null) {
            return JSON.toJSONString(new ReturnDto(-1, "记账金额必填", null));
        }
        //保存数据
        BookKeep bookKeep = bookKeepService.create(bookKeepVM, userOptional.get());
        return JSON.toJSONString(new ReturnDto(1, "创建成功", new BookKeepDto(bookKeep)));
    }

    @PutMapping("/book-keep/{id}")
    public String update(@PathVariable Integer id,@RequestBody BookKeepVM bookKeepVM,HttpServletRequest request){
        //获取jwt
        String token = JwtUtil.getJwtFromRequest(request);
        if(StringUtils.isBlank(token)){
            return JSON.toJSONString(new ReturnDto(-1, "非法请求", null));
        }
        String userId;
        try {
            userId = JwtUtil.parseToken(token);
        }catch (Exception e){
            return JSON.toJSONString(new ReturnDto(-9, "token过期", null));
        }
        Optional<User> userOptional = userRepository.findById(Integer.parseInt(userId));
        if(!userOptional.isPresent()){
            return JSON.toJSONString(new ReturnDto(-1, "不存在该用户", null));
        }

        //必填写段的判断
        if(!userOptional.isPresent()){
            return JSON.toJSONString(new ReturnDto(-1, "不存在该用户", null));
        }
        //检验必填字段
        if (StringUtils.isBlank(bookKeepVM.getCagegory())) {
            return JSON.toJSONString(new ReturnDto(-1, "分类必填", null));
        }
        if (bookKeepVM.getBookKeepDate() == null) {
            return JSON.toJSONString(new ReturnDto(-1, "记账时间必填", null));
        }
        if (bookKeepVM.getType() == null) {
            return JSON.toJSONString(new ReturnDto(-1, "记账类型必填", null));
        }
        //这里大家可以多加一些判断，比如，金额传0报错，
        if (bookKeepVM.getPrice() == null) {
            return JSON.toJSONString(new ReturnDto(-1, "记账金额必填", null));
        }
        Optional<BookKeep> bookKeepById = bookKeepRepository.findById(id);
        if (!bookKeepById.isPresent()) {
            return JSON.toJSONString(new ReturnDto(-1, "系统中不存在该数据", null));
        }
        // 编辑接口
        BookKeep bookKeep = bookKeepService.update(bookKeepById.get(), bookKeepVM);
        return JSON.toJSONString(new ReturnDto(1, "修改成功", new BookKeepDto(bookKeep)));
    }

    //删除接口
    @DeleteMapping("/book-keep/{id}")
    public String delete(@PathVariable Integer id,HttpServletRequest request){
        // 获取jwt
        String token = JwtUtil.getJwtFromRequest(request);
        if (StringUtils.isBlank(token)) {
            return JSON.toJSONString(new ReturnDto(-1, "非法请求", null));
        }
        String userId;
        try {
            userId = JwtUtil.parseToken(token);
        } catch (Exception e) {
            return JSON.toJSONString(new ReturnDto(-9, "token过期", null));
        }
        Optional<User> userOptional = userRepository.findById(Integer.parseInt(userId));
        if (!userOptional.isPresent()) {
            return JSON.toJSONString(new ReturnDto(-1, "不存在该用户", null));
        }
        Optional<BookKeep> bookKeep = bookKeepRepository.findById(id);
        if (!bookKeep.isPresent()) {
            return JSON.toJSONString(new ReturnDto(-1, "系统中不存在该数据", null));
        }
        bookKeepService.delete(bookKeep.get());
        return JSON.toJSONString(new ReturnDto(1, "删除成功", null));
    }

}
